public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode hair1 = new ListNode(-1);
        ListNode hair2 = new ListNode(-1);
        hair1.next = head;
        hair2.next = head;
        ListNode fast = hair1;
        ListNode slow = hair2;

        while (fast != slow) {
            if (fast.next == null || fast.next.next == null) {return null;}
            fast = fast.next.next;
            slow = slow.next;
        }
        fast = hair1;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}